//
//  YHCountDownButton.swift
//  Adorbee
//
//  Created by amovision on 2024/11/29.
//

import UIKit

public class YHCountDownButton: UIButton {
  public enum State: Int {
    case start, running, stop
  }

  public var timeout = 60 {
    didSet {
      timer.repeatCount = timeout
    }
  }

  public var countdownBlock: ((UIButton, YHCountDownButton.State, Int) -> Void)? = nil

  private lazy var timer: YHTimer = .init(repeatCount: self.timeout) { [weak self] cd, isFinished in
    guard let self else { return }
    if isFinished {
      countdownBlock?(self, .stop, 0)
    } else {
      countdownBlock?(self, .running, self.timeout - cd)
    }
    isEnabled = isFinished
  }

  public func start() {
    countdownBlock?(self, .start, timeout)
    isEnabled = false
    timer.fire()
  }
}
